package com.hly.utils;

import javafx.util.Pair;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class FyUtils {
    private static String filePathRoot = "D:\\tmp\\"; // 指定 xlsx 文件的路径
    private static String fileName = "工作簿 (1).xlsx"; // 指定 xlsx 文件的路径
    private static String mXlsxPath = filePathRoot + fileName; // 指定 xlsx 文件的路径
    public static boolean isPrintSpecifications = true;
    public static boolean isPrintStringsXml = true;
    public static boolean isNullXml = false;

    public static LinkedHashMap<Integer, String> keyNameMap = new LinkedHashMap<Integer, String>();
    private static LinkedHashMap<String, List<Pair<Integer, XmlBean>>> fyMap = new LinkedHashMap<String, List<Pair<Integer, XmlBean>>>();
    public static LinkedHashMap<String, String> writeFilePathMap = new LinkedHashMap<>();
    private static String directoryName = "";
    private static String keyName = "编码";
//    private static String keyName = "keyName";

    private static LinkedHashMap<String, String> androidValueMap = new LinkedHashMap<String, String>();
    public static StringBuffer errorStringBuffer = new StringBuffer();

    public static List<String> fuhaoList = new ArrayList<>();

    private static String customTag = "<(!-CustomTag-!)>";

    static {
        androidValueMap.put("汉语", "values-zh-rCN");
        androidValueMap.put("汉文", "values-zh-rCN");
        androidValueMap.put("中文", "values-zh-rCN");
        androidValueMap.put("中国", "values-zh-rCN");
        androidValueMap.put("中文简体", "values-zh-rCN");

        androidValueMap.put("香港", "values-zh-rHK");
        androidValueMap.put("粤语", "values-zh-rHK");
        androidValueMap.put("香港简体", "values-zh-rHK");

        androidValueMap.put("台湾", "values-zh-rTW");
        androidValueMap.put("台语", "values-zh-rTW");
        androidValueMap.put("台湾简体", "values-zh-rTW");

        androidValueMap.put("英语", "values-en");
        androidValueMap.put("英文", "values-en");
        androidValueMap.put("英国", "values-en");

        androidValueMap.put("意大利语", "values-it-rIT");
        androidValueMap.put("意大利文", "values-it-rIT");
        androidValueMap.put("意大利国", "values-it-rIT");
        androidValueMap.put("意大利", "values-it-rIT");

        androidValueMap.put("西班牙语", "values-es-rES");
        androidValueMap.put("西班牙文", "values-es-rES");
        androidValueMap.put("西班牙国", "values-es-rES");
        androidValueMap.put("西班牙", "values-es-rES");

        androidValueMap.put("波兰语", "values-pl-rPL");
        androidValueMap.put("波兰文", "values-pl-rPL");
        androidValueMap.put("波兰国", "values-pl-rPL");
        androidValueMap.put("波兰", "values-pl-rPL");

        androidValueMap.put("日语", "values-ja-rJP");
        androidValueMap.put("日文", "values-ja-rJP");
        androidValueMap.put("日本", "values-ja-rJP");
        androidValueMap.put("日本语", "values-ja-rJP");
        androidValueMap.put("日本国", "values-ja-rJP");

        androidValueMap.put("德语", "values-de-rDE");
        androidValueMap.put("德文", "values-de-rDE");
        androidValueMap.put("德国", "values-de-rDE");

        androidValueMap.put("俄语", "values-ru-rRU");
        androidValueMap.put("俄文", "values-ru-rRU");
        androidValueMap.put("俄国", "values-ru-rRU");

        androidValueMap.put("法语", "values-fr-rFR");
        androidValueMap.put("法文", "values-fr-rFR");
        androidValueMap.put("法国", "values-fr-rFR");

        androidValueMap.put("韩语", "values-ko-rKR");
        androidValueMap.put("韩文", "values-ko-rKR");
        androidValueMap.put("韩国", "values-ko-rKR");

        androidValueMap.put("泰语", "values-th-rTH");
        androidValueMap.put("泰文", "values-th-rTH");
        androidValueMap.put("泰国", "values-th-rTH");
    }

    public static void main(String[] args) {
        //打印规范
        //建议的命名规则 目录
        mXlsxPath = filePathRoot + fileName;
        FyUtils.handlerContent(mXlsxPath);
    }

    public static Map<String, LinkedHashMap<String, XmlBean>> handlerContent(String xlsxPath) {
        mXlsxPath = xlsxPath;
        if (isPrintSpecifications) {
            errorStringBuffer.append("建议的命名规则").append("\n");
            printToast();
            printDialog();
            errorStringBuffer.append("\n\n");
        }
        //新建文件夹
        return parseData();

    }


    private static void printDialog() {
        for (int i = 0; i < 5; i++) {
            printStringHtml("common_dialog_" + (i + 1), "xxx");
        }
    }

    private static void printToast() {
        for (int i = 0; i < 5; i++) {
            printStringHtml("common_toast_" + (i + 1), "xxx");
        }
    }

    private static Map<String, LinkedHashMap<String, XmlBean>> parseData() {
        Map<String, LinkedHashMap<String, XmlBean>> xmlBeanMap = new LinkedHashMap<>();
        String writeContent = "";
        String writePath = "";
        try {
            keyNameMap.clear();
            fyMap.clear();
            if (!new File(mXlsxPath).exists()) {
                System.out.println("不存在");
                return Collections.emptyMap();
            }
            Workbook workbook = new XSSFWorkbook(new FileInputStream(mXlsxPath)); // 创建工作簿对象
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个表格页（索引从0开始）
            int rowNum = sheet.getRow(0).getLastCellNum();
            int index = 0;
            boolean isFirst = true;
            int subIndex = 0;
            for (int i = 0; i < rowNum; i++) {
                index = 0;
                subIndex = -1;
                for (Row row : sheet) {//一列的每一行
                    subIndex++;
                    //每一列的值
                    Cell rowTextNull = row.getCell(i);
                    if(null==rowTextNull){
//                        throw new RuntimeException("xlsx中存在空行 index="+i+"---subIndex="+subIndex);
                        continue;
                    }
                    String rowText = row.getCell(i).toString();
                    if (isVailName(row.getCell(i))) {
                        break;
                    }
                    if (isKeyName(rowText)) {
                        isFirst = true;
                    } else {
                        if (index != 0) {
                            //翻译列表
                            List<Pair<Integer, XmlBean>> fyList = fyMap.get(directoryName);
                            if (null == fyList) {
                                fyList = new ArrayList<>();
                            } else {
                                if (!fyList.isEmpty()) {
//                                    System.out.println("有数据" + fyList);
                                }
                            }
                            if (isFirst) {
                                keyNameMap.put(subIndex, rowText);
                            } else {
                                XmlBean xmlBean = getStringXmlBean(keyNameMap.get(subIndex), rowText);
                                fyList.add(new Pair<>(subIndex, xmlBean));
                                if (!"".equals(directoryName)) {
                                    fyMap.put(directoryName, fyList);
                                }
                            }
                        } else {
                            //目录
                            if (directoryName.equals("")) {
                                System.out.println("=================================xlsx中需要翻译的语言 开始================================");
                            }
                            directoryName = rowText;
                            System.out.println("");
                            System.out.println("语言：" + directoryName);
                            //创建目录
                            new File(filePathRoot + directoryName + File.separator + androidValueMap.get(directoryName)).mkdirs();
                            fyMap.put(directoryName, new ArrayList<>());
                        }
                    }
                    index++;
                }
                isFirst = false;
            }
            workbook.close(); // 关闭工作簿
            System.out.println("=================================xlsx中需要翻译的语言 结束================================");
            System.out.println("");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            printKeyName();
            writeFilePathMap = printCreateFile();
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, List<Pair<Integer, XmlBean>>> entry : fyMap.entrySet()) {
//                if(isKeyName(entry.getKey())){
//                    continue;
//                }
                List<Pair<Integer, XmlBean>> pairList = entry.getValue();
                LinkedHashMap<String, XmlBean> subXmlBeanMap = new LinkedHashMap<>();
                sb.delete(0, sb.length());
                sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\n");
                sb.append("<resources xmlns:tools=\"http://schemas.android.com/tools\">").append("\n");
                sb.append("\t").append("<!-- " + entry.getKey() + "翻译 -->").append("\n");

                writePath = writeFilePathMap.get(entry.getKey());

                for (int i = 0; i < pairList.size(); i++) {
                    Pair<Integer, XmlBean> pairValue = pairList.get(i);
                    String keyName = keyNameMap.get(pairValue.getKey());
                    XmlBean xmlBean = pairValue.getValue();
                    sb.append("\t").append(xmlBean.getFullContent().replace(customTag, keyName)).append("\n");
//                    sb.append("\t").append(xmlBean.getFullContentTemp()).append("\n");
                    xmlBean.setWritePath(writePath);
                    subXmlBeanMap.put(keyName, xmlBean);
                }
                sb.append("</resources>");
                writeContent = sb.toString();
                //将内容写入文件
                if (isPrintStringsXml) {
                    System.out.println("===========================即将被替换更新的" + entry.getKey() + "的strings.xml文件 开始================================");
                    System.out.println(writeContent);
                    System.out.println("===========================即将被替换更新的" + entry.getKey() + "的strings.xml文件 结束================================");
//                    errorStringBuffer.append("=================================" + entry.getKey() + "的strings.xml文件 开始================================").append("\n");
//                    errorStringBuffer.append(writeContent).append("\n");
//                    errorStringBuffer.append("=================================" + entry.getKey() + "的strings.xml文件 结束================================").append("\n");
                }
                System.out.println("");//new Pair<>(writePath, writeContent)
//                errorStringBuffer.append("\n");
                xmlBeanMap.put(entry.getKey(), subXmlBeanMap);
            }
        }
        return xmlBeanMap;
    }

    private static boolean isVailName(Cell cell) {
        return "备注".equals(cell)||"截图".equals(cell);
    }

    private static LinkedHashMap<String, String> printCreateFile() {
//        System.out.println("=================================创建语言对应的strings.xml文件 开始================================");
        errorStringBuffer.append("=================================创建语言对应的strings.xml文件 开始================================").append("\n");
        LinkedHashMap<String, String> writeFilePathMap = new LinkedHashMap<>();
        for (Map.Entry<String, List<Pair<Integer, XmlBean>>> entry : fyMap.entrySet()) {
            File file = new File(filePathRoot + entry.getKey() + File.separator + androidValueMap.get(entry.getKey()) + File.separator + "strings.xml");
            createFile(file);
            writeFilePathMap.put(entry.getKey(), file.getAbsolutePath());
//            System.out.println("创建文件：" + file.getAbsolutePath());
            errorStringBuffer.append("创建文件：" + file.getAbsolutePath()).append("\n");
        }
//        System.out.println("=================================创建语言对应的strings.xml文件 结束================================");
        errorStringBuffer.append("=================================创建语言对应的strings.xml文件 结束================================").append("\n");
        System.out.println("");
        return writeFilePathMap;
    }

    private static void printKeyName() {
        System.out.println("=================================xlsx中定义好的keyName 开始================================");
        for (String key : keyNameMap.values()) {
            System.out.println(key);
        }
        System.out.println("=================================xlsx中定义好的keyName 结束================================");
        System.out.println();
    }

    private static void createFile(File file) {
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
        }
    }

    private static void printStringHtml(String moduleName, String content) {
//        System.out.println("<string name=\"" + moduleName + "\">" + content + "</string>");
        errorStringBuffer.append("<string name=\"" + moduleName + "\">" + content + "</string>").append("\n");
        ;
    }

    private static XmlBean getStringXmlBean(String moduleName, String content) {
        XmlBean xmlBean = new XmlBean("getStringXmlBean", moduleName, content, "<string name=\"" + moduleName + "\">" + content + "</string>");
        return xmlBean;
    }

    public static boolean isKeyName(String rowText){
        String rowTextTmp = rowText.replace("\n", "");
        if (keyName.equalsIgnoreCase(rowTextTmp)||keyName.equals("keyName")||"keyName".equals(rowTextTmp)) {
            return true;
        }
        return false;
    }
}